package com.gykfbxxh.imovie.custom.net;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.app.utils.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gykfbxxh.imovie.base.bean.DataBean;
import com.gykfbxxh.imovie.config.AppConfigTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.manager.AppConfigManager;

import java.util.HashMap;
import java.util.Map;

/**
 * 制作一个 Gson的get请求
 * Makes a get request and converts the response from JsonElement into a
 * list of objects/object using with Google Gson.
 * Created by xuxinghai on 2016/6/12.
 */
public class GsonGetResultRequest extends Request
{
    private final Gson gson;
    private final Response.Listener listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param listener is the listener for the right answer
     * @param errorListener  is the listener for the wrong answer
     */
    public GsonGetResultRequest
    (
            @NonNull final String url,
            @NonNull final Gson gson,
            @NonNull final Response.Listener listener,
            @NonNull final Response.ErrorListener errorListener
    )
    {
        super(Method.GET, url, errorListener);

        this.gson = gson;
        this.listener = listener;
    }


    @Override
    protected Response parseNetworkResponse(NetworkResponse response)
    {

        try
        {
            /**
             * 获取用户Token
             */
            Map<String, String> headers = response.headers;
            String headerValue = headers.get("Set-Cookie");
            if (!TextUtils.isEmpty(headerValue)) {
                String[] tokens = headerValue.split(";");
                for (int i = 0; i < tokens.length; i++) {
                    String token = tokens[i].trim();
                    if (token.equals("no-cache") || token.equals("no-store")) {
                        break;
                    } else if (token.startsWith("mortise_loginToken=")) {
                        try {
                            String tokenStr = token.substring(19);
                            if(!TextUtils.isEmpty(tokenStr)) {
                                LogUtils.e("xuxh","LoginToken="+tokenStr);
                                AppConfigTools.TOKENSTR = tokenStr ;
                                SharedPreferences.Editor editor = AppConfigManager.getInstance().getEditor();
                                editor.putString(ConfigKey.user_token,tokenStr);
                                editor.commit();
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            }

            String json = new String(response.data);

            if(TextUtils.isEmpty(json)){
                json = DataBean.getDefaultJson();
            }
            return (Response)Response.success
                    (
                            json,
                            HttpHeaderParser.parseCacheHeaders(response)
                    );
        }
        catch (JsonSyntaxException e)
        {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(Object result) {
        if(this.listener != null) {
            listener.onResponse(result);
        }
    }

    /**
     * header
     * @return
     * @throws AuthFailureError
     */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> head = new HashMap<>();
        if(TextUtils.isEmpty(AppConfigTools.TOKENSTR)) {
            String tokenStr = AppConfigManager.getInstance().readConfig(ConfigKey.user_token, "");
            if(!TextUtils.isEmpty(tokenStr)) {
                head.put("Cookie","mortise_loginToken="+tokenStr);
            }
        }else {
            head.put("Cookie","mortise_loginToken="+AppConfigTools.TOKENSTR);
        }
        return head;
    }
}
